package club.jdiy.core.base;


import club.jdiy.utils.DateUtils;

import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Date;
import java.util.Objects;

/**
 * for:springMVC Date类型自动映射转换识别
 *
 * @author ziquee(子秋) QQ号:39886616 主页: http://www.jdiy.club
 * @version 20200520
 */
public class Java8MyDateEditor extends PropertyEditorSupport {
    public enum Type {
        LocalDateTime, LocalDate, Date
    }

    public Java8MyDateEditor(Type t) {
        Objects.requireNonNull(t, "无效Type类型绑定");
        this.t = t;
    }

    /**
     * text是表单传入的数据内容
     */
    @Override
    public void setAsText(String text) {
        if (text == null || "".equals(text.trim())) return;
        if (Type.LocalDate.equals(t)) {
            setValue(LocalDate.parse(text, DateUtils.fmt_date));
        } else if (Type.LocalDateTime.equals(t)) {
            setValue(LocalDateTime.parse(text, formatter));
        } else {
            Date value = null;
            if (!"".equals(text)) {
                for (String pattern : patterns) {
                    try {
                        value = new SimpleDateFormat(pattern).parse(text);
                        break;
                    } catch (Exception ignore) {
                    }
                }
            }
            setValue(value);
        }
    }

    private final Type t;
    private final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("yyyy-MM-dd[[' 'HH][:mm][:ss]]")
            .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
            .toFormatter();
    private static final String[] patterns = new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd"};
}